using System;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CodRevit.Handlers;

namespace CodRevit.ViewModels
{
    public partial class ChangeCategoryViewModel : ObservableObject
    {
        private readonly UIApplication _uiApp;
        private readonly ExternalEvent _externalEvent;
        private readonly ChangeCategoryHandler _handler;
        private readonly List<FamilyInstance> _preSelectedFamilyInstances;

        public ChangeCategoryViewModel(UIApplication uiApp, ExternalEvent externalEvent, ChangeCategoryHandler handler, List<FamilyInstance> preSelectedFamilyInstances)
        {
            _uiApp = uiApp;
            _externalEvent = externalEvent;
            _handler = handler;
            _preSelectedFamilyInstances = preSelectedFamilyInstances;

            // 初始化可用的族类别
            InitializeAvailableCategories();
            
            // 设置默认选择为常规模型
            SelectedCategory = AvailableCategories.FirstOrDefault(c => c.Name == "常规模型");
            
            // 显示预选择的族信息
            var familyCount = _preSelectedFamilyInstances.GroupBy(f => f.Symbol.Family.Id).Count();
            StatusMessage = $"已选择 {_preSelectedFamilyInstances.Count} 个族实例，包含 {familyCount} 个不同的族";
        }

        [ObservableProperty]
        private ObservableCollection<CategoryItem> _availableCategories = new();

        [ObservableProperty]
        private CategoryItem? _selectedCategory;

        [ObservableProperty]
        private string _statusMessage = string.Empty;

        [ObservableProperty]
        private bool _isProcessing = false;

        [ObservableProperty]
        private ObservableCollection<string> _processedFamilies = new();

        [ObservableProperty]
        private bool _hasProcessedFamilies = false;

        [RelayCommand]
        private void Execute()
        {
            try
            {
                if (SelectedCategory == null)
                {
                    StatusMessage = "请选择目标族类别";
                    return;
                }

                if (!_preSelectedFamilyInstances.Any())
                {
                    StatusMessage = "没有可用的族实例";
                    return;
                }

                IsProcessing = true;
                StatusMessage = "正在处理...";
                ProcessedFamilies.Clear();

                // 按族ID分组，避免同一族被重复处理
                var familyGroups = _preSelectedFamilyInstances
                    .GroupBy(e => e.Symbol.Family.Id)
                    .Select(g => g.First())
                    .ToList();

                StatusMessage = $"找到 {familyGroups.Count} 个族，正在修改类别...";

                // 配置处理器参数
                _handler.SetParameters(familyGroups, SelectedCategory.BuiltInCategory, this);

                // 执行外部事件
                _externalEvent.Raise();
            }
            catch (Exception ex)
            {
                StatusMessage = $"执行失败: {ex.Message}";
                IsProcessing = false;
            }
        }

        [RelayCommand]
        private void Clear()
        {
            ProcessedFamilies.Clear();
            StatusMessage = string.Empty;
            IsProcessing = false;
        }

        private void InitializeAvailableCategories()
        {
            var categories = new List<CategoryItem>
            {
                new CategoryItem("专用设备", BuiltInCategory.OST_SpecialityEquipment),
                new CategoryItem("场地", BuiltInCategory.OST_Site),
                new CategoryItem("家具", BuiltInCategory.OST_Furniture),
                new CategoryItem("常规模型", BuiltInCategory.OST_GenericModel),
                new CategoryItem("柱", BuiltInCategory.OST_Columns),
                new CategoryItem("植物", BuiltInCategory.OST_Planting),
                new CategoryItem("环境", BuiltInCategory.OST_Entourage),
                new CategoryItem("门", BuiltInCategory.OST_Doors),
                new CategoryItem("窗", BuiltInCategory.OST_Windows),
                new CategoryItem("结构连接", BuiltInCategory.OST_StructConnections)
            };

            AvailableCategories = new ObservableCollection<CategoryItem>(categories);
        }

        public void OnProcessCompleted(List<string> processedFamilyNames, string message)
        {
            try
            {
                if (Application.Current?.Dispatcher != null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        ProcessedFamilies.Clear();
                        foreach (var familyName in processedFamilyNames)
                        {
                            ProcessedFamilies.Add(familyName);
                        }
                        HasProcessedFamilies = ProcessedFamilies.Count > 0;
                        StatusMessage = message;
                        IsProcessing = false;
                    });
                }
                else
                {
                    // 回退方案：直接设置属性
                    ProcessedFamilies.Clear();
                    foreach (var familyName in processedFamilyNames)
                    {
                        ProcessedFamilies.Add(familyName);
                    }
                    HasProcessedFamilies = ProcessedFamilies.Count > 0;
                    StatusMessage = message;
                    IsProcessing = false;
                }
            }
            catch (Exception ex)
            {
                // 如果Dispatcher调用失败，直接设置属性作为回退
                StatusMessage = message;
                IsProcessing = false;
                System.Diagnostics.Debug.WriteLine($"OnProcessCompleted异常: {ex.Message}");
            }
        }

        public void OnProcessFailed(string errorMessage)
        {
            try
            {
                if (Application.Current?.Dispatcher != null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        StatusMessage = $"处理失败: {errorMessage}";
                        IsProcessing = false;
                    });
                }
                else
                {
                    // 回退方案：直接设置属性
                    StatusMessage = $"处理失败: {errorMessage}";
                    IsProcessing = false;
                }
            }
            catch (Exception ex)
            {
                // 如果Dispatcher调用失败，直接设置属性作为回退
                StatusMessage = $"处理失败: {errorMessage}";
                IsProcessing = false;
                System.Diagnostics.Debug.WriteLine($"OnProcessFailed异常: {ex.Message}");
            }
        }
    }

    public class CategoryItem
    {
        public CategoryItem(string name, BuiltInCategory builtInCategory)
        {
            Name = name;
            BuiltInCategory = builtInCategory;
        }

        public string Name { get; set; }
        public BuiltInCategory BuiltInCategory { get; set; }

        public override string ToString()
        {
            return Name;
        }
    }
}